import pygame
from pygame.locals import *
from pygame import *
import sys

class label(pygame.sprite.Sprite):
    def __init__(self, text, size, xpos, ypos, application):
        # Load label as image
        image = self.loadlabel(text, size, xpos, ypos, application)
        # Add to spritelist
        application.spritelist.append(image)
        # Render all items in spritelist
        application.spritegrouprender = pygame.sprite.OrderedUpdates(application.spritelist)
        # Draw rendered group
        application.spritegrouprender.draw(pygame.display.get_surface())
        # Show
        pygame.display.flip()

    def loadlabel(self, text, size, xpos, ypos, application):
        # Call sprite initializer
        pygame.sprite.Sprite.__init__(self)
        #font = pygame.font.Font(application.font, application.fontsize)
        font = pygame.font.Font(application.font, size)
        font.set_bold(application.fontbold)
        font.set_italic(application.fontitalic)
        # Backup some stuff
        self.size = size
        self.xpos = xpos
        self.ypos = ypos
        l = len(text)
        # Surfacesize
        self.tilex = pygame.display.get_surface().get_rect().width / application.divx
        self.tiley = pygame.display.get_surface().get_rect().height / application.divy
        # Get actual res for X
        if xpos <> "center":
            xpos = self.tilex * xpos
        # Get actual res for Y
        if ypos <> "center":
            ypos = self.tiley * ypos
        # Calc the size
        label_text = font.render(text, 1, application.fontcolor)
        while self.size * self.tilex < label_text.get_rect().width:
            l -= 1
            text = text[0:l]
            label_text = font.render(text, 1, application.fontcolor)
        label_text_pos = label_text.get_rect()
        # X center
        if xpos == "center":
            xpos = pygame.display.get_surface().get_rect().centerx  - label_text.get_rect().width/2
        # Y center
        if ypos == "center":
            ypos = pygame.display.get_surface().get_rect().centery  - label_text.get_rect().height/2
        self.image = label_text
        self.rect = self.image.get_rect()
        self.rect.x = xpos
        self.rect.y = ypos
        return self

    def change(self, text, application):
        image = self.loadlabel(text, self.size, self.xpos, self.ypos, application)
        application.spritegrouprender.draw(pygame.display.get_surface())
        pygame.display.flip()
